package ru.spbau.krasko.phonelock.main;

import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.Backlight;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.Sensor;
import net.rim.device.api.system.SensorListener;
import net.rim.device.api.system.SystemListener2;
import net.rim.device.api.ui.UiApplication;
import ru.spbau.krasko.phonelock.settings.Settings;
import ru.spbau.krasko.phonelock.settings.SettingsScreen;

/**
 * This class extends the UiApplication class, providing a graphical user
 * interface.
 */
public class PhoneLockApp extends UiApplication {
	private LockScreen lockScreen = LockScreen.INSTANCE;

	class BacklightListener implements SystemListener2 {
		public void powerUp() {
		}

		public void powerOff() {
		}

		public void batteryStatusChange(int status) {
		}

		public void batteryLow() {
		}

		public void batteryGood() {
		}

		public void usbConnectionStateChange(int state) {
		}

		public void powerOffRequested(int reason) {
		}

		public void fastReset() {
		}

		public void cradleMismatch(boolean mismatch) {
		}

		public void backlightStateChange(boolean on) {
			boolean backlightRunningDown = !on;
			boolean sliderStateAllowsLock = !Sensor.isSupported(Sensor.SLIDE)
					|| Sensor.getState(Sensor.SLIDE) != Sensor.STATE_SLIDE_OPEN;
			if (backlightRunningDown && sliderStateAllowsLock) {
				lockScreen.lock();
			}
		}
	}

	public PhoneLockApp() {
		Settings.addApplication(ApplicationDescriptor.currentApplicationDescriptor());
		
		pushScreen(new SettingsScreen());

		getUiEngineInstance().setAcceptableDirections(Display.DIRECTION_NORTH);
		Sensor.addListener(this, new SensorListener() {
			public void onSensorUpdate(int sensorId, int update) {
				switch (update) {
				case Sensor.STATE_SLIDE_OPEN:
					lockScreen.unlock();
					break;
				case Sensor.STATE_SLIDE_CLOSED:
					if (Settings.isEnabled(Settings.LOCK_ON_SLIDER_CLOSE)
							|| !Backlight.isEnabled()) {
						lockScreen.lock();
					}
					break;
				}
			}
		}, Sensor.SLIDE);
	}

	public boolean shouldAppearInApplicationSwitcher() {
		return false;
	}

	public static void main(String[] args) {
		PhoneLockApp theApp = new PhoneLockApp();
		theApp.addSystemListener(theApp.new BacklightListener());

		theApp.enterEventDispatcher();
	}
}
